package com.eras.shoes.ui;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.eras.shoes.R;
import com.eras.shoes.contents.Api;
import com.eras.shoes.contents.Global;
import com.eras.shoes.contents.UserConfigBean;
import com.eras.shoes.contents.UserInfo;
import com.eras.shoes.utils.OkHttpUtils;
import com.eras.shoes.utils.ToastUtils;
import com.google.android.datatransport.backend.cct.BuildConfig;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Request;

public class UserInfoDetail extends AppCompatActivity {

    TextView tvAccount;
    TextView tvFactory;
    TextView tvProductionLine;
    TextView tvWorkStation;
    TextView tvRoleXm;
    TextView tvVersion;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info);

        // 设置界面显示
        tvAccount = ((TextView)findViewById(R.id.tvAccount));//
        tvFactory = ((TextView)findViewById(R.id.tvFactory));//.setText("工厂: " + factory);
        tvProductionLine = ((TextView)findViewById(R.id.tvProductionLine));//.setText("产线: " + productionLine);
        tvWorkStation = ((TextView)findViewById(R.id.tvWorkStation));//.setText("工位: " + workStation);
        tvRoleXm = ((TextView)findViewById(R.id.tvRoleXm));//.setText("角色: " + roleXm);
        tvVersion = ((TextView)findViewById(R.id.tvVersion));//.setText("角色: " + roleXm);
        ((TextView)findViewById(R.id.tv_user_info_back)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        ((TextView)findViewById(R.id.tv_user_info_exit)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                signOut();
            }
        });

        setVersionInfo();

    }

    private void setVersionInfo() {
        try {
            PackageInfo packageInfo = getPackageManager()
                    .getPackageInfo(getPackageName(), 0);

            String versionName = packageInfo.versionName; // "CXJC_V1.0.5"
            int versionCode = packageInfo.versionCode;     // 6

            String versionText = String.format("版本：%s (VersionCode %d)", versionName, versionCode);
            tvVersion.setText(versionText);

        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            tvVersion.setText("版本信息获取失败");
        }
}

    @Override
    protected void onStart() {
        super.onStart();
        getUserDetail();
        getUserConfig();
    }

    private void setLoginOut(Context context){
        Global.token = "";
        //公司
        Global.companyCode = "";//
        Global.companyName = "";
        Global.companyConfig = "";
        //训练仪
        Global.wordCode = "";//
        Global.wordName = "";
        Global.wordConfig = "";
        //特征词
        Global.shoesCode = "";//ZH和XZ
        Global.shoesName = "";
        Global.shoesConfig = "";
        //款型
        Global.serialCode = "";
        Global.serialName = "";
        Global.serialConfig = "";
        //颜色
        Global.colorCode = "";
        Global.colorlName = "";
        Global.colorConfig = "";
        //大小
        Global.sizeCode = "";
        Global.sizelName = "";
        Global.sizeConfig = "";
        //规格代码
        Global.specificationCode = "";
        Global.specificationName = "";
        Global.specificationConfig = "";
        //左右脚
        Global.footCode = "";
        Global.footName = "";
        Global.footConfig = "";
        SharedPreferences sharedPref = context.getSharedPreferences("login_prefs", Context.MODE_PRIVATE);
        if (sharedPref != null) {
            SharedPreferences.Editor editor = sharedPref.edit();
            editor.putString("username", "")
                    .putString("password", "")
                    .putString("token", "")
                    .putBoolean("is_auto_login", false);
            editor.apply();
        }
    }

    private void signOut() {
        OkHttpUtils.postJsonAsync(UserInfoDetail.this, Api.signOut, "", new OkHttpUtils.DataCallBack() {
            @Override
            public void requestFailure(Request request, IOException e) {

            }

            @Override
            public void requestSuccess(String result) throws Exception {
                JSONObject toJsonObj = new JSONObject(result);
                int code = toJsonObj.getInt("code");
                if (code == 0) {
                    setLoginOut(UserInfoDetail.this);
                    String message = (String) toJsonObj.get("message");
                    new ToastUtils().show(UserInfoDetail.this, "退出" + message);
                    Intent intent = new Intent(UserInfoDetail.this, LoginActivity.class);
                    startActivity(intent);
                    finish();
                }
            }
        });
    }

    private void setUserConfig(String company,String featureWords,String coreWords,String modelCode,String specificationCode,String footType,String color,String shoeSize,String mobileCode) {
        UserConfigBean user = new UserConfigBean();
        user.setCompany(company);
        user.setFeatureWords(featureWords);
        user.setCoreWords(coreWords);
        user.setModelCode(modelCode);
        user.setSpecificationCode(specificationCode);
        user.setFootType(footType);
        user.setColor(color);
        user.setShoeSize(shoeSize);
        user.setMobileCode(mobileCode);
        String data = new Gson().toJson(user);
        OkHttpUtils.postJsonAsync(UserInfoDetail.this, Api.updateConfig, data, new OkHttpUtils.DataCallBack() {
            @Override
            public void requestFailure(Request request, IOException e) {

            }

            @Override
            public void requestSuccess(String result) throws Exception {
                JSONObject toJsonObj = new JSONObject(result);
                int code = toJsonObj.getInt("code");
                if (code == 0) {
                } else {
                    String message = (String) toJsonObj.get("message");
                    new ToastUtils().show(UserInfoDetail.this, message);
                }
            }
        });
    }

    private void getUserDetail() {
        OkHttpUtils.getAsyncToken(UserInfoDetail.this, Api.userInfo, true, new OkHttpUtils.DataCallBack() {
            @Override
            public void requestFailure(Request request, IOException e) {

            }

            @SuppressLint("SetTextI18n")
            @Override
            public void requestSuccess(String result) throws Exception {
                JSONObject toJsonObj = new JSONObject(result);
                Log.e("UserInfoDetail", "返回"+toJsonObj);
                int code = toJsonObj.getInt("code");
                if (code == 0) {
                    if (result.contains("data")) {
                        String jsonData = toJsonObj.getString("data");
                        UserInfo userInfo = new Gson().fromJson(jsonData, UserInfo.class);
                        tvAccount.setText("账号: " + userInfo.getAccount());
                        tvFactory.setText("工厂: " + userInfo.getFactory());
                        tvProductionLine.setText("产线: " + userInfo.getProductionLine());
                        tvWorkStation.setText("工位: " + userInfo.getWorkStation());
                        StringBuilder builder = new StringBuilder();
                        int size = userInfo.getRoleNames().size();
                        for (int i = 0; i < size; i++) {
                            builder.append(userInfo.getRoleNames().get(i));
                            if (i < size-1) {
                                builder.append("、");
                            }
                        }
                        tvRoleXm.setText("角色: " + builder.toString());
                    }
                }

            }
        });
    }
    private void getUserConfig() {
        OkHttpUtils.getAsyncToken(UserInfoDetail.this, Api.getConfig, true, new OkHttpUtils.DataCallBack() {
            @Override
            public void requestFailure(Request request, IOException e) {

            }

            @SuppressLint("SetTextI18n")
            @Override
            public void requestSuccess(String result) throws Exception {
                JSONObject toJsonObj = new JSONObject(result);
                Log.e("UserInfoDetail", "返回"+toJsonObj);
                int code = toJsonObj.getInt("code");
                if (code == 0) {
                    if (result.contains("data")) {
                        String jsonData = toJsonObj.getString("data");
                        UserConfigBean userInfo = new Gson().fromJson(jsonData, UserConfigBean.class);
                        new UserConfigBean(userInfo.getCompany(), userInfo.getFeatureWords(), userInfo.getCoreWords(), userInfo.getModelCode(), userInfo.getSpecificationCode(), userInfo.getFootType(), userInfo.getColor(), userInfo.getShoeSize(), userInfo.getMobileCode());

                    }
                }

            }
        });
    }

}
